<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="96px"
    >
      <el-form-item label="合同编号" prop="contractNo">
        <el-input
          v-model="queryParams.contractNo"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="责任人" prop="contractResponsiblePersonId">
        <el-select
          v-model="queryParams.contractResponsiblePersonId"
          placeholder="请选择合同责任人"
          clearable
          filterable
          class="!w-240px"
          :filter-method="getUserList"
        >
          <el-option
            v-for="dict in userList"
            :key="dict.id"
            :label="dict.nickname"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同状态" prop="contractStatus">
        <el-select
          v-model="queryParams.contractStatus"
          placeholder="请选择合同状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CONTRACT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="合同名称" prop="contractName">
        <el-input
          v-model="queryParams.contractName"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="签订时间" prop="signingDate">
        <el-date-picker
          v-model="queryParams.signingDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:contract:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:contract:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="合同编号" align="center" prop="contractNo" />
      <el-table-column label="合同名称" align="center" prop="contractName" />
      <el-table-column label="甲方名称" align="center" prop="partyA" />
      <el-table-column label="签订时间" align="center" prop="signingDate">
        <template #default="scope">
          {{ formatDate(scope.row.signingDate, 'YYYY-MM-DD') }}
        </template>
      </el-table-column>
      <el-table-column label="乙方名称" align="center" prop="partyB" />
      <el-table-column label="合同状态" align="center" prop="contractStatus">
        <template #default="scope">
          <!-- {{ scope.row.contractStatus }} -->
          <dict-tag :type="DICT_TYPE.CONTRACT_STATUS" :value="scope.row.contractStatus" />
        </template>
      </el-table-column>
      <el-table-column label="合同责任人" align="center" prop="contractResponsiblePerson" />
      <!-- <el-table-column label="合同文件" align="center" prop="imageList" /> -->
      <el-table-column label="操作" align="center" min-width="120px" fixed="right">
        <template #default="scope">
          <!-- <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:contract:update']"
          >
            发起签批
          </el-button> -->
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:contract:update']"
            v-if="scope.row.contractStatus == 'UN_AUDIT'"
          >
            编辑
          </el-button>
          <el-button link @click="openForm('detail', scope.row.id)"> 详情 </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:contract:delete']"
            v-if="scope.row.contractStatus == 'UN_AUDIT'"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ContractForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import { getSimpleUserList, UserVO } from '@/api/system/user' // 角色
import download from '@/utils/download'
import { ContractApi, ContractVO } from '@/api/erp/contract'
import ContractForm from './ContractForm.vue'

/** 合同信息 列表 */
defineOptions({ name: 'Contract' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ContractVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  contractName: undefined,
  contractNo: undefined,
  contractStatus: undefined,
  signingDate: [],
  partyA: undefined,
  partyB: undefined,
  contractType: undefined,
  contractTaxRate: undefined,
  contractAmountInclTax: undefined,
  contractAmountExclTax: undefined,
  contractDepartmentId: undefined,
  contractDepartment: undefined,
  contractResponsiblePersonId: undefined,
  contractResponsiblePerson: undefined,
  responsiblePersonPhone: undefined,
  partyAManagerId: undefined,
  partyAManager: undefined,
  partyBDepartment: undefined,
  partyBResponsiblePerson: undefined,
  partyBManagerPhone: undefined,
  partyBManager: undefined,
  partyBManagerWx: undefined,
  partyBManagerEmail: undefined,
  urgencyLevel: undefined,
  confidentialityLevel: undefined,
  effectiveDate: [],
  expirationDate: [],
  renewalDate: [],
  contractSummary: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ContractApi.getContractPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 获取人员列表 */
const userList = ref<UserVO[]>([])
// const getUserList = async () => {
//   try {
//     const data = await getSimpleUserList()
//     userList.value = data
//   } catch (err) {
//     console.error('获取用户列表失败:', err)
//   }
// }
const getUserList = async (query?: string) => {
  console.log('filtering with query:', query)
  const data = await getSimpleUserList()
  if (!query) {
    userList.value = data.slice(0, 200)
    return userList.value
  }
  userList.value = data.filter((d) => d.nickname.toLowerCase().includes(query.toLowerCase()))
  return userList.value
}

/** 搜索按钮操作 */
const handleQuery = () => {
  if (queryParams.signingDate.length > 0) {
    queryParams.signingDate[0] = queryParams.signingDate[0] + ' 00:00:00'
    queryParams.signingDate[1] = queryParams.signingDate[1] + ' 23:59:59'
  }
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ContractApi.deleteContract(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ContractApi.exportContract(queryParams)
    download.excel(data, '合同信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getUserList()
})
</script>